package com.zone.vehicle.superapp.datasource;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.DownloadHelper;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.db.gen.DownloadDao;
import com.zone.lib.download.install.AndroidP;
import com.zone.lib.download.utils.AppStatusUpdateNotify;
import com.zone.lib.download.utils.DateUtils;
import com.zone.lib.download.utils.DownloadUtil;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.appstore.request.AppsDetailRequest;
import com.zone.sdk_api.ApiManager;
import com.zone.vehicle.sdk.module.superapp.entity.AppUpdateEntity;
import com.zone.vehicle.sdk.module.superapp.request.AppPushRequest;
import com.zone.vehicle.sdk.module.superapp.request.AppsUpdateListRequest;
import com.zone.vehicle.sdk.module.superapp.response.AppPushResponse;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.utils.SharedPreferencesUtil;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.util.List;

import static com.zone.sdk_api.common.Content.USER_ID;
import static com.zone.sdk_api.common.Content.VIN;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class AppManagerDataSource {
    private static final String TAG = "AppManagerDataSource";
    /**
     * 获取执行中APP：下载、安装
     * @param type
     * @return
     */
    public List<Download> getActivityApps(AppTypeEnum type){
        List<Download> list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.AppType.eq(type.getCode()));
        return list;
    }

    /**
     * oldVersion不为空即认为是已安装应用
     * @param type
     * @return
     */
    public List<Download> getLocalInstalledApps(AppTypeEnum type){
        QueryBuilder<Download> queryBuilder = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().getQueryBuilder();
        queryBuilder.where(DownloadDao.Properties.AppType.eq(type.getCode()),
                queryBuilder.or(DownloadDao.Properties.DownloadStatus.eq(AppStatusEnum.INSTALL_SUCCESS.CODE),
                        DownloadDao.Properties.LastVersion.isNotNull()));
        List<Download> list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(queryBuilder);
        return list;
    }

    public List<Download> getLocalApps(AppTypeEnum type, AppStatusEnum appStatusEnum){
        // TODO 未接入安装，暂时将下载完成状态APP查询出来
        List<Download> list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.AppType.eq(type.getCode()), DownloadDao.Properties.DownloadStatus.eq(appStatusEnum.CODE));
        return list;
    }

    public List<Download> getDownloadApps(AppTypeEnum type){
        List<Download> list ;
        if (ObjectUtils.isEmpty(type)){
            list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.DownloadStatus.notIn(AppStatusEnum.INSTALL_SUCCESS.CODE, AppStatusEnum.LIGHT_INSTALL_COMPLETE.CODE));
        } else {
            list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.AppType.eq(type.getCode()), DownloadDao.Properties.DownloadStatus.notIn(AppStatusEnum.INSTALL_SUCCESS.CODE, AppStatusEnum.LIGHT_INSTALL_COMPLETE.CODE));
        }
        return list;
    }

    public List<Download> getInstallApps(AppTypeEnum type){
        List<Download> list = null;
        if (ObjectUtils.isEmpty(type)){
            list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.DownloadStatus.notIn(AppStatusEnum.INSTALL_SUCCESS.CODE, AppStatusEnum.LIGHT_INSTALL_COMPLETE.CODE));
        } else if(type == AppTypeEnum.APP){
            list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.AppType.eq(type.getCode()), DownloadDao.Properties.DownloadStatus.eq(AppStatusEnum.INSTALL_SUCCESS.CODE));
        } else if(type == AppTypeEnum.APP_LIGHT){
            list = DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().queryByQueryBuilder(DownloadDao.Properties.AppType.eq(type.getCode()), DownloadDao.Properties.DownloadStatus.eq(AppStatusEnum.LIGHT_INSTALL_COMPLETE.CODE));
        }
        return list;
    }

    public void downLoadApp(Context context, int status, AppDetailEntity appEntity){
        if (ObjectUtils.isNotEmpty(appEntity)){
            File dir = new File(context.getCacheDir(), "download");
            if (!dir.exists()){
                dir.mkdirs();
            }
            File saveFile = new File(dir, appEntity.getCode()+".apk");
            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
            if (ObjectUtils.isEmpty(download)){
                download = DownloadUtil.build(status, appEntity, saveFile);
                DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().insert(download);
//                DownloadHelper.getInstance().addTask(appEntity.getCode(), saveFile, status, Long.parseLong(ObjectUtils.isEmpty(appEntity.getSize())?"0":appEntity.getSize()), appEntity.getVersion(), SharedPreferencesUtil.getInstance(context).getSP("vin")).submit(context);
                DownloadHelper.getInstance().addTask(saveFile, SharedPreferencesUtil.getInstance(context).getSP(VIN), status, appEntity, download).submit(context);
            } else {
                //暂停 或者 继续
                if (status == AppStatusEnum.DOWNLOAD_PAUSE.CODE
                        || status == AppStatusEnum.DOWNLOAD_PREPARE.CODE
                ){
                    DownloadHelper.getInstance().addTask(saveFile, SharedPreferencesUtil.getInstance(context).getSP(VIN), status, appEntity, download).submit(context);
                }
            }
        }
    }

    public void updateApp(Context context, int status, AppBean appBean){
        if (ObjectUtils.isNotEmpty(appBean)){
            File dir = new File(context.getCacheDir(), "download");
            if (!dir.exists()){
                dir.mkdirs();
            }
            File saveFile = new File(dir, appBean.getCode()+".apk");
            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appBean.getCode());
            if (ObjectUtils.isNotEmpty(download)){
                DownloadDaoUtilsStore.getInstance().deleteByCode(download.getCode());
                File delete = new File(download.getFilePath());
                if (delete.exists()){
                    delete.delete();
                }
                AppUpdateEntity updateEntity = appBean.getUpdateEntity();
                Download downloadNew = DownloadUtil.build(status, appBean, saveFile);
                if (ObjectUtils.isNotEmpty(downloadNew)) {
                    downloadNew.setLastVersion(download.getVersion());
                    downloadNew.setVersion(updateEntity.getNewVersion());
                    downloadNew.setDownloadStatus(AppStatusEnum.DOWNLOAD_PREPARE.CODE);
                    DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().insert(downloadNew);
                    DownloadHelper.getInstance().addTask(saveFile, SharedPreferencesUtil.getInstance(context).getSP(VIN), status, appBean, downloadNew).submit(context);
                }
            }
        }
    }

    public void getAppDetail(Context context, String code, ResultCallBack<Result<AppDetailEntity>> callBack){
        AppsDetailRequest request = new AppsDetailRequest();
        request.setSpuId(code);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appsDetail(request, callBack);
    }

    public void appList(List<String> codeList, ResultCallBack<Result<List<AppEntity>>> callBack){
        AppsDetailRequest request = new AppsDetailRequest();
        request.setCodeList(codeList);
        ApiManager.getInstance().appList(request, callBack);
    }

    public void appletPush(Context context, AppDetailEntity appEntity, AppStatusEnum statusEnum, ResultCallBack<Result<AppPushResponse>> callback){
        AppPushRequest request = new AppPushRequest();
        request.setAppCode(appEntity.getCode());
        if (statusEnum == AppStatusEnum.DOWNLOAD_PREPARE) {
            request.setActive("1");//下载
        }else if (statusEnum == AppStatusEnum.DOWNLOAD_PAUSE) {
            request.setActive("3");//下载
        }else if (statusEnum == AppStatusEnum.DOWNLOAD_CONTINUE) {
            request.setActive("4");//下载
        }else if (statusEnum == AppStatusEnum.LIGHT_DELETE){
            request.setActive("2");//卸载
        }
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setAppType(appEntity.getAppType());
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appPush(request, callback);
    }

    public void updateList(Context context, String appCode, AppTypeEnum appTypeEnum, ResultCallBack<Result<List<AppUpdateEntity>>> callback){
        AppsUpdateListRequest request = new AppsUpdateListRequest();
        request.setAppCode(appCode);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        request.setType(appTypeEnum.getName());
        ApiManager.getInstance().updateList(request, callback);
    }

    public void delete(Context context, AppDetailEntity appEntity){
        if (ObjectUtils.isNotEmpty(appEntity) && StringUtils.isNotEmpty(appEntity.getPackageName())) {
            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
            if (ObjectUtils.isNotEmpty(download)) {
                if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE) {
                    if (AndroidP.uninstall(context, appEntity.getCode(), download.getPackageName())) {
                        Log.e(TAG, "uninstall app failed  " + download.getPackageName());
                        return;
                    }
                }
                download.setDownloadStatus(AppStatusEnum.DOWNLOAD_DELETE.CODE);
                AppStatusUpdateNotify.appNotify(context, download);
                Log.d(TAG, "delete app " + download);
                DownloadHelper.getInstance().deleteTask(context, appEntity.getCode());
                File file = new File(download.getFilePath());
                // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
                if (file.exists() && file.isFile()) {
                    file.delete();
                }
                DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().delete(download);
            }
        }
    }

    public void install(Context context, AppDetailEntity appEntity, AppStatusEnum statusEnum){
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
        if (ObjectUtils.isEmpty(download)){
            return;
        }
        if (statusEnum == AppStatusEnum.INSTALL_PREPARE && (
                download.getDownloadStatus() != AppStatusEnum.DOWNLOAD_COMPLETE.CODE
                        || download.getDownloadStatus() != AppStatusEnum.INSTALL_FAIL.CODE
        )){
            AndroidP.install28(context, download);
        }else if (statusEnum == AppStatusEnum.UNINSTALL_APP && download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE){
            AndroidP.uninstall(context, appEntity.getCode(), download.getPackageName());
        }
    }
}